package com.hn.zhijian.web.config.jwt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hn.zhijian.base.common.StatusCode;
import com.hn.zhijian.base.model.response.Response;
import com.hn.zhijian.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @program: carl-main
 * @description: JWT拦截器
 * @author: carl
 * @create: 2019-12-09 23:12
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {


    private static final String USER_TOKEN = "Authorization";

    /**
     * 判断用户是否想要登入。
     * 检测header里面是否包含Authorization字段即可
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader(USER_TOKEN);
        return authorization != null;
    }


//    /**
//     * 执行登录认证
//     *
//     * @param request
//     * @param response
//     * @param mappedValue
//     * @return
//     */
//    @Override
//    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
////        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
////        String url = httpServletRequest.getServletPath();
////        String token = httpServletRequest.getHeader(USER_TOKEN);
////        if (Utils.isEmpty(token) && "/account/login".equals(url)) {
////            //可能是游客或者登录
////            return true;
////        }
//        try {
//            executeLogin(request, response);
//            return true;
//        } catch (Exception e) {
//            return false;
//        }
//    }

    /**
     *
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(USER_TOKEN);
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    //登录失败时默认返回 401 状态码
    private void onLoginFail(ServletResponse response, int code, String message) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        Response model = new Response();
        model.setCode(code);
        model.setMessage(message);
        model.setNow(new Date());
        sendMessage(httpResponse, model);
    }

    private void sendMessage(HttpServletResponse httpResponse, Response model) throws IOException {
        JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
        //解决@ref
        SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect;
        //解决null对象
        SerializerFeature writeMapNullValue = SerializerFeature.WriteMapNullValue;
        //解决""字段
        SerializerFeature writeNullStringAsEmpty = SerializerFeature.WriteNullListAsEmpty;
        //解决时间long转成固定时间格式
        SerializerFeature writeDateUseDateFormat = SerializerFeature.WriteDateUseDateFormat;

        httpResponse.setHeader("Content-type", "text/html;charset=UTF-8");

        httpResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());

        httpResponse.getWriter().write(JSON.toJSONString(model, feature, writeMapNullValue, writeNullStringAsEmpty, writeDateUseDateFormat));


    }


    /**
     * 返回结果为true表明登录通过
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        log.warn("onAccessDenied 方法被调用");
        //这个地方和前端约定，要求前端将jwtToken放在请求的Header部分

        //所以以后发起请求的时候就需要在Header中放一个Authorization，值就是对应的Token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(USER_TOKEN);
        log.info("请求的 Header 中藏有 jwtToken {}", token);
        JwtToken jwtToken = new JwtToken(token);
        /*
         * 下面就是固定写法
         * */
        try {
            // 委托 realm 进行登录认证
            //所以这个地方最终还是调用JwtRealm进行的认证
            getSubject(servletRequest, servletResponse).login(jwtToken);
            //也就是subject.login(token)
        } catch (Exception e) {
            //调用下面的方法向客户端返回错误信息
            onLoginFail(servletResponse, StatusCode.UNAUTHORIZED.getCode(), StatusCode.UNAUTHORIZED.getMessage());
            return false;
        }
        return true;
    }


    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
